package com.data.structure.sparsearray;


/**
 * 稀疏数组
 *
 * @author wangjie
 * @version V1.0
 * @date 2019/12/18
 */
public class SparseArray {

    public static void main(String[] args) {
        
        int[][] chessArr1 = new int[11][11];
        chessArr1[1][2] = 1;
        chessArr1[5][5] = 2;
        print(chessArr1);
        int[][] ints = arrayToSparseArray(chessArr1);
        print(ints);
        int[][] ints1 = sparseArrayToArray(ints);
        print(ints1);

    }


    /**
     * 打印日志
     * @param array
     */
    private static  void print(int[][] array){

        for (int[] arr : array){
            for (int ar : arr){
                System.out.printf("%d\t",ar);
            }
            System.out.println();
        }
        System.out.println("----------------------------------------");

    }

    /**
     * 将二维数组转为稀疏数组
     * @param array
     * @return
     */
    private static int[][] arrayToSparseArray(int[][] array){

        //1.先得到非0个数
        int sum = 0;
        for(int i = 0; i < array.length ; i++){
            for (int j = 0; j < array.length ; j++){
                if(0 != array[i][j]){
                    sum++;
                }
            }
        }
        //2.创建稀疏数组
        int sparseArray[][] = new int[sum+1][3];
        sparseArray[0][0] = array.length;
        sparseArray[0][1] = array.length;
        sparseArray[0][2] = sum;

        //3.给稀疏数组赋值
        int count = 0;
        for(int i = 0; i < array.length ; i++){
            for (int j = 0; j < array.length ; j++){
                if(0 != array[i][j]){
                    count++;
                    sparseArray[count][0] = i;
                    sparseArray[count][1] = j;
                    sparseArray[count][2] = array[i][j];
                }
            }
        }
        return sparseArray;

    }

    /**
     * 稀疏数组转二维数组
     * @param sparseArray
     * @return
     */
     private static int[][] sparseArrayToArray(int[][] sparseArray){

         //1.先读取稀疏数组第一行，创建二维数组
         int array[][] = new int[sparseArray[0][0]][sparseArray[0][1]];
         //2.给二维数组赋值
         for(int i = 1;i < sparseArray.length;i++){
             array[sparseArray[i][0]][sparseArray[i][1]] = sparseArray[i][2];
         }

         return array;
     }
}

